package com.lhnstart.learn.gather;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

/**
 * Java中Comparable和Comparator区别小结
 *
 * @author lhn
 * @date 2022/09/13 09:04
 * @since 1.0.0
 **/
public class Comparable2ComparatorDemo {

    @Test
    public void compatibleSort() {
        Person[] people=new Person[]{new Person("xujian", 20),new Person("xiewei", 10)};
        System.out.println("排序前");
        Arrays.stream(people).forEach(System.out::println);
        System.out.println("排序后");
        Arrays.sort(people);
        Arrays.stream(people).forEach(System.out::println);
    }

    @Test
    public void comparatorSort() {
        Person[] people=new Person[]{new Person("xujian", 20),new Person("xiewei", 10)};
        System.out.println("排序前");
        Arrays.stream(people).forEach(System.out::println);
        System.out.println("排序后");
        Arrays.stream(people).sorted((p1, p2) -> {
            return p1.getAge() - p2.getAge();
        }).forEach(System.out::println);

        PersonComparator personComparator = new PersonComparator();
        System.out.println(personComparator.compare(people[0], people[1]));
        //Arrays.sort(people, PersonComparator.class);
        //Arrays.stream(people).forEach(System.out::println);
    }

}

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
@ToString
class Person implements Comparable<Person>
{
    private String name;
    private int age;

    @Override
    public int compareTo(Person o) {
        return this.age - o.getAge();
    }
}

class PersonComparator implements Comparator <Person> {

    @Override
    public int compare(Person o1, Person o2) {
        return o1.getAge() - o2.getAge();
    }
}